/*
 * Copyright 2007 Mojo Chen
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * Nymex Crude Future
 * yahoo currency convert
 * 
 * http://finance.yahoo.com/currency?u
 * 
 * http://download.finance.yahoo.com/d/quotes.csv?s=USDTWD=X&f=sl1d1t1ba&e=.csv
 * "USDTWD=X",32.3685,"10/29/2007","3:03am",32.3635,32.3735
 * 
 * http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=sl1d1t1ba&e=.csv
 * "USDEUR=X",0.6938,"10/29/2007","3:04am",0.6938,0.6939
 * 
 * http://download.finance.yahoo.com/d/quotes.csv?s=EURTWD=X&f=sl1d1t1ba&e=.csv
 * "EURTWD=X",46.672,"10/29/2007","3:22am",46.66,46.6841
 * 
 * get javascript object form text
 * var json = new Function("return "+req.responseText)();
 * 
 * gold url
 * 
 * http://dgcsc.org/goldprices2.xml
 * 
 * Gold 100 oz(ounce) , 1 oz = 28.3495231 gram
 * 
 * http://download.finance.yahoo.com/d/quotes.csv?s=ZGV07.CBT&f=sl1d1t1c1ohgv&e=.csv
 * "ZGV07.CBT",793.70,"10/29/2007","1:46am",+9.60,793.70,793.70,793.70,0
 * 
 * oil
 * 
 * http://download.finance.yahoo.com/d/quotes.csv?s=CLZ07.NYM&f=sl1d1t1c1ohgv&e=.csv
 * "CLZ07.NYM",92.73,"10/29/2007","5:36am",+0.87,91.72,93.20,90.60,0
 * 
 * 
 * 
 */
var linkxdGold = {
	
	_timer : null,
	
	myGold : {},
	
	loopCount:0,
	
	goldXmlUrl : 'http://dgcsc.org/goldprices2.xml',
	usdTwdUrl : 'http://download.finance.yahoo.com/d/quotes.csv?s=USDTWD=X&f=sl1d1t1ba&e=.csv',
	usdEurUrl : 'http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=sl1d1t1ba&e=.csv',
	eurTwdUrl : 'http://download.finance.yahoo.com/d/quotes.csv?s=EURTWD=X&f=sl1d1t1ba&e=.csv',
	usdOilUrl : 'http://download.finance.yahoo.com/d/quotes.csv?s=CLZ07.NYM&f=sl1d1t1c1ohgv&e=.csv',
	
	// change symbol need.
	usdGoldHtml : 'http://finance.yahoo.com/q?s=ZGV07.CBT',
	usdGoldUrl : 'http://download.finance.yahoo.com/d/quotes.csv?s=ZGV07.CBT&f=sl1d1t1c1ohgv&e=.csv',
	
	// oil TODO
	usdOilHtml : 'http://finance.yahoo.com/q?s=CLZ07.NYM',
	eurTwdHtml : 'http://finance.yahoo.com/q?s=EURTWD%3DX',
	usdTwdHtml : 'http://finance.yahoo.com/q?s=USDTWD%3DX',
	
	getUsdGoldHtml:function(){
		if(!this.goldSymbol){
			this.goldSymbol = this.getGoldFutureSymbol();
		}
		return 'http://finance.yahoo.com/q?s='+this.goldSymbol;
	},
	
	getUsdGoldUrl:function(){
		if(!this.goldSymbol){
			this.goldSymbol = this.getGoldFutureSymbol();
		}
		return 'http://download.finance.yahoo.com/d/quotes.csv?s=' +
				this.goldSymbol +
				'&f=sl1d1t1c1ohgv&e=.csv';
	},
	
	getGoldFutureSymbol: function(){
		// TODO 
		// gold future symbol change problem
		// Gold 100 oz. Oct 07 (CBOT:ZGV07.CBT)
		// Gold 100 oz. Nov 07 (CBOT:ZGX07.CBT)
		// FUTURES CHAIN
		// ZGZ07.CBT	Gold 100 oz. Dec 07
		// ZGG08.CBT	Gold 100 oz. Feb 08
		// ZGJ08.CBT	Gold 100 oz. Apr 08
		// ZGM08.CBT	Gold 100 oz. Jun 08
		// ZGQ08.CBT	Gold 100 oz. Aug 08
		// ZGV08.CBT	Gold 100 oz. Oct 08
		// ZGZ08.CBT	Gold 100 oz. Dec 08
		// G J M Q V Z
		
		var arr = ['G','J','M','Q','V','Z'];
		
		var date = new Date();
		var yearCode = String(date.getFullYear()).substr(2,2);
		// 11,12 = 6
		// 1,2 = 1
		var monthNum = Math.ceil((date.getMonth()+1)/2);
		var symbol = "ZG" + arr[monthNum-1] + yearCode + '.CBT';
		linkxdMain.log('getGoldFutureSymbol', 'Get symbol ' + symbol + ' at ' + date);		
		return symbol;
	},
	
	onTest: function(){
		linkxdGold.invokeMyGold();
  	},
  	
  	getHref:function(url,text){
  		return '<a href="' +
  				url +
  				'" target="_blank" style="text-decoration:none;">'+text+'</a>';
  	},
  	
  	getPasteHtml:function(){
  		linkxdMain.log('info','Get Paste Gold Html.');
  		var gold = linkxdGold.myGold;
			// Gold oz(ounce) , 1 oz = 28.3495231 gram
		var twdAsk = gold.usdGold * gold.usdTwd / 28.3495231;
		var goldGram = 10000/twdAsk;
		var eur = 10000/gold.eurTwd;
		var usd = 10000/gold.usdTwd;
		var twdOil = 10000/(gold.usdTwd*gold.usdOil);
		// 1000 gram = 26.6667
			
		var usdGoldHref = this.getHref(this.getUsdGoldHtml(),'金價一盎司' + gold.usdGold +'美元');
		var usdOilHref = this.getHref(this.usdOilHtml,'油價一桶' + gold.usdOil+'美元');
		var usdTwdHref = this.getHref(this.usdTwdHtml, usd.toFixed(2)+'美元');
		var eurTwdHref = this.getHref(this.eurTwdHtml, eur.toFixed(2)+'歐元');
		var goldGramHref = this.getHref(this.getUsdGoldHtml(),'黃金' + goldGram.toFixed(2)+'公克');
		var twdOilHref = this.getHref(this.usdOilHtml,'石油' + twdOil.toFixed(2)+'桶');
		//http://win.dgbas.gov.tw/dgbas03/bs9/price_cpi_curv/cpi_curv.asp
		// TWD 10000@86 = 11075@96
		var twdTenYear = 10000*10/11075;
		var text =  '根據' +
				gold.date +
				'的即時資料，目前的' +
							usdGoldHref +
							'、' +
							usdOilHref+'，' +
				'手上拿著台幣千元鈔10張可換到' +
					goldGramHref +
					'、' +
					twdOilHref +
					'、' +
					eurTwdHref +
					'、' +
					usdTwdHref+'，十年後剩下' +
							twdTenYear.toFixed(2) +
							'張。';
		return text;
  	},
  	
    invokeMyGold: function(callback){
    	
    	linkxdMain.log('info','invoke MyGold()');
    	
    	linkxdGold.callback = callback;
		
		// FIXME??
		
		try{
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			this.invokeYahooData(this.usdTwdUrl);
			this.invokeYahooData(this.eurTwdUrl);
			//this.invokeYahooData(this.usdGoldUrl);
			this.invokeYahooData(this.getUsdGoldUrl());
			this.invokeYahooData(this.usdOilUrl);
			//this.invokeGoldXml();
			linkxdGold.loopCount = 0;
			this._timer = setInterval(linkxdGold.doTimer, 1000);
		// wait??
		}catch(err){
			alert(err + ' in linkxdGold.invokeMyGold()');
		}
  	},
  	
  	doTimer : function() {
  		
  		linkxdGold.loopCount +=1;
  		linkxdMain.log('doTimer()','check loop count:' + linkxdGold.loopCount);
  		
  		if(linkxdGold.loopCount > 10){
  			linkxdMain.log('doTimer() Error','loop count over limit 10, stop timer');
    		clearInterval(linkxdGold._timer);
    		return;  			
  		}
  		
  		var gold = linkxdGold.myGold;
    	if (linkxdGold._timer && gold.usdTwdDone && gold.eurTwdDone && gold.usdGoldDone && gold.usdOilDone){
    		clearInterval(linkxdGold._timer);
    		//linkxdGold.printMyGold();
    		linkxdGold.callback();
    	} else {
    		var tmp = 'usdTwdDone:' + gold.usdTwdDone;
    		tmp += ',eurTwdDone:' + gold.eurTwdDone;
    		tmp += ',usdGoldDone:' + gold.usdGoldDone;
    		tmp += ',usdOilDone:' + gold.usdOilDone;
  			linkxdMain.log('doTimer()',tmp);
    	}
    	// do something??
    	
    },
  	
  	printMyGold : function(){
  		var result = "Get the gold:";
  		result +="eurTwd:" + this.myGold.eurTwd + "\r\n";
  		result +="usdTwd:" + this.myGold.usdTwd + "\r\n";
  		//result +="usdAsk:" + this.myGold.usdAsk + "\r\n";
  		//result +="eurAsk:" + this.myGold.eurAsk + "\r\n";
  		alert(result);
  	},
  	
    invokeYahooData: function(url){
    	
    	try{
    	   	//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			var req = new XMLHttpRequest();
  			req.open('GET', url, true);
  			req.onreadystatechange = function(aEvt) {
    	   		//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  				if (req.readyState == 4) {
  					if(req.status == 200){
  						try{
  							linkxdGold.parseYahooCsv(req.responseText);
  							
  						}catch(err){
  							linkxdMain.log('Error',err + ' in XMLHttpRequest.responseText');
  						}
  					}else{
  						linkxdMain.log('Error',"Error loading page");
  					}
  				}
  			};
  			req.send(null);
    	} catch(err){
    		alert(err + " : invokeYahooData()");
    	} 
  	},
	
	invokeGoldXml: function(){
		
  		var req = new XMLHttpRequest();
  		
  		req.overrideMimeType('text/xml');
  		req.open('GET', this.goldXmlUrl, true);
  		
  		req.onreadystatechange = function(aEvt) {
  			if (req.readyState == 4) {
  				if(req.status == 200){
  					var result = linkxdGold.getGoldJson(req.responseXML);
  					//alert('EUR Bid = ' + result.eurBid);
  					//alert('EUR Ask = ' + result.eurAsk);
  					//alert('USD Ask = ' + result.usdAsk);
  					//alert('USD Bid = ' + result.usdBid);
  				}else{
  					alert("Error loading " + this.goldXmlUrl);
  				}
  			}
  		};
  		req.send(null); 
  	},
  	
  	parseYahooCsv: function(csvDoc){
  		try{
  		//"EURTWD=X",46.672,"10/29/2007","3:22am",46.66,46.6841
  		//"USDTWD=X",32.3685,"10/29/2007","3:03am",32.3635,32.3735
  		// "ZGV07.CBT",793.70,"10/29/2007","1:46am",+9.60,793.70,793.70,793.70,0
  		//"CLZ07.NYM",92.73,"10/29/2007","5:36am",+0.87,91.72,93.20,90.60,0
  		var dataArr = csvDoc.split(",");
  		var symbol = dataArr[0];
  		var price = dataArr[1];
  		var date = dataArr[2];
  	 	linkxdMain.log('parseYahooCsv','Get ' +
  	 			symbol +
  	 			':' + price);
  		
  		if(symbol.match("USDTWD")){
  			this.myGold.usdTwd = price;
  			this.myGold.date = date;
  			this.myGold.usdTwdDone = true;
  	 		linkxdMain.log('parseYahooCsv','usdTwdDone is true now.');
  		} else if(symbol.match("EURTWD")){  			
  			this.myGold.eurTwd = price;
  			this.myGold.eurTwdDone = true;
  	 		linkxdMain.log('parseYahooCsv','eurTwdDone is true now.');
  		} else if(symbol.match(this.goldSymbol)){  			
  			this.myGold.usdGold = price;
  			this.myGold.usdGoldDone = true;
  	 		linkxdMain.log('parseYahooCsv','goldDone is true now.');
  		} else if(symbol.match("CLZ07")){  			
  			this.myGold.usdOil = price;
  			this.myGold.usdOilDone = true;
  	 		linkxdMain.log('parseYahooCsv','usdOilDone is true now.');
  		}}catch(err){
  			alert(err +' in linkxdGold.parseYahooCsv()');
  		}
  	},
	
	getGoldJson:function(xmlDoc){
  		try{
  			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
  			var priceIterator = xmlDoc.evaluate('/GoldPrice/Price[@currencycode="EUR" or @currencycode="USD"]', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
  			var priceNode = priceIterator.iterateNext();
  			//var foo = "foo:";
  			while(priceNode){
  				ccode = priceNode.getAttribute('currencycode');
  				var ask = priceNode.childNodes[0].textContent;// ask
  				var bid = priceNode.childNodes[1].textContent;// bid
  							
  				if(ccode == "EUR"){
  					this.myGold.eurAsk = ask;
  					this.myGold.eurBid = bid;
  					//alert(goldJson.eurBid);
  								
  				} else if(ccode == "USD"){
  					this.myGold.usdAsk = ask;
  					this.myGold.usdBid = bid;
  				}
  							
				priceNode = priceIterator.iterateNext();
  			}
  						
  			//alert('USD ASK :'+ goldJson.usdAsk);
  						
  			}catch(err){
  				alert(err);
  			}
  		this.myGold.goldAskDone = true;
  			//alert(req.responseText + '\r\n');
  		return this.myGold;
	}

};
